<template>
  <eip-modal
    :visible="visible"
    :title="'回收站(' + title + ')'"
    @close="cancel"
    width="90%"
    :height="800"
  >
    <template slot="body">
      <div>
        <a-card
          class="eip-admin-card-small"
          :loading="grid.loading"
          :bordered="false"
        >
          <vxe-grid
            v-if="!grid.loading"
            v-bind="grid"
            ref="recycleBin"
            :cellStyle="cellStyle"
          >
            <template #toolbar_buttons>
              <a-space>
                <a-button icon="retweet" type="link" @click="delRecovery">
                  恢复选中
                </a-button>

                <a-button type="link" @click="delPhysics">
                  <span class="text-red"
                    ><a-icon type="delete" /> 彻底删除</span
                  >
                </a-button>

                <a-button type="link" @click="delPhysicsAll">
                  <span class="text-red"
                    ><a-icon type="delete" /> 立即清空</span
                  >
                </a-button>
              </a-space>
            </template>

            <template #toolbar_tools> </template>

            <template #loading>
              <a-spin></a-spin>
            </template>

            <template #empty>
              <eip-empty />
            </template>

            <template #checkboxHeader="{ checked, indeterminate }">
              <span @click.stop="$refs.recycleBin.toggleAllCheckboxRow()">
                <a-checkbox :indeterminate="indeterminate" :checked="checked">
                </a-checkbox>
              </span>
            </template>
            <!-- 多选 -->
            <template #checkbox="{ row, checked, indeterminate }">
              <span @click.stop="$refs.recycleBin.toggleCheckboxRow(row)">
                <a-checkbox :indeterminate="indeterminate" :checked="checked">
                </a-checkbox>
              </span>
            </template>
            <!-- 单选 -->
            <template #radio="{ row, checked }">
              <span @click.stop="$refs.recycleBin.toggleCheckboxRow(row)">
                <a-radio :checked="checked"> </a-radio>
              </span>
            </template>
            <!-- 序号 -->
            <template #seq="">
              <span>序号</span>
            </template>
            <template #seqdefalut="{ row }">
              <div
                v-if="
                  cellStyle({ row }) &&
                  [0, 1].includes(cellStyle({ row }).showType)
                "
                class="flex justify-between align-center"
              >
                <span> {{ row.row_num }}</span>
                <span
                  class="colorTag"
                  :style="{
                    'background-color': cellStyle({ row }).showTypeColor,
                  }"
                >
                </span>
              </div>
              <span v-else>
                {{ row.row_num }}
              </span>
            </template>
            <!-- 格式化内容 -->
            <template #default="{ row, column }">
              <list-content
                :row="row"
                :column="column"
                :type="convertType(column)"
                :options="getOptions(column)"
              ></list-content>
            </template>
          </vxe-grid>
        </a-card>
      </div>
    </template>
    <template slot="footer">
      <div class="flex justify-between align-center">
        <div></div>
        <a-space>
          <a-button @click="cancel"><a-icon type="close" />关闭</a-button>
        </a-space>
      </div>
    </template></eip-modal
  >
</template>

<script>
import listContent from "@/pages/system/zerocode/run/components/list/content";
import { findById } from "@/services/system/zerocode/view/designer";
import {
  query,
  delPhysics,
  delPhysicsAll,
  delRecovery,
  gridCustomFindByKey,
  gridCustomSave,
} from "@/services/system/zerocode/run/list";
import { mapMutations, mapGetters } from "vuex";
import { selectTableRow, deleteConfirm, operationConfirm } from "@/utils/util";
import { VxeUI } from "vxe-pc-ui";
export default {
  data() {
    return {
      tooltipConfig: {
        showAll: true,
        enterable: true,
        contentMethod: ({ type, column, row, items, _columnIndex }) => {
          if (type == "header") {
            return "";
          }
          const { field } = column;
          if (row) {
            var columnFilter = this.table.columns.filter(
              (f) => f.field == field
            );
            if (columnFilter != null && columnFilter.length > 0) {
              var data = columnFilter[0];
              switch (data.format) {
                case "Map":
                  if (row[field]) {
                    return JSON.parse(row[field]).address;
                  }
                  break;
                case "File":
                case "Image":
                  if (row[field]) {
                    return "";
                  }
                  break;
              }
              if (data.style.length > 0) {
                var style = data.style.filter(
                  (f) => f.value == row[field.replace("_Txt", "")]
                );
                return style.length > 0 ? style[0].content : "";
              }
            }
            if (column.title == "操作") {
              return "";
            }

            var value = row[field];
            if (value) {
              return value;
            }
          }
          // 其余的单元格使用默认行为
          return null;
        },
      },

      grid: {
        loading: true,
      }, //列表配置

      publicJson: {}, //发布配置
      columnJson: {}, //字段配置
      settingJson: {},
      interval: null,

      title: "",
      formZeroCodeId: "",
      gridCustom: {
        fixedData: null,
        resizableData: null,
        sortData: null,
        visibleData: null,
      },
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    //低代码Id
    zeroCodeId: {
      type: String,
    },
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  components: {
    listContent,
  },
  watch: {
    //若有改变则赋予属性
    zeroCodeId(val) {
      if (val) {
        this.initGrid();
        this.reloadData();
      }
    },
  },
  created() {
    this.initGrid();
  },
  methods: {
    /**
     *初始化列表配置项
     */
    async initGridOption() {
      let that = this;
      //默认排序
      let option = this.publicJson;
      let zeroCodeId = this.zeroCodeId;
      let title = this.$route.name;
      let columns = await that.initColumn();
      this.grid = {
        size: option.style.size,
        border: option.style.border,
        stripe: option.style.stripe,
        id: "recycleBin",
        loading: true,
        height: 660,
        sortConfig: {
          trigger: "cell",
          defaultSort: this.initSorts(),
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        checkboxConfig: {
          reserve: true,
        },
        radioConfig: {
          reserve: true,
        },
        expandConfig: {
          reserve: true,
        },
        rowConfig: {
          keyField: "RowId",
        },
        customConfig: {
          storage: true,
          mode: "popup",
          restoreStore({ storeData }) {
            return true;
          },
          updateStore({ id, type, storeData }) {
            let resizableData = that.$utils.merge(
              that.gridCustom.resizableData,
              storeData.resizableData
            );
            let fixedData = that.$utils.merge(
              that.gridCustom.fixedData,
              storeData.fixedData
            );
            let sortData = that.$utils.merge(
              that.gridCustom.sortData,
              storeData.sortData
            );
            let visibleData = that.$utils.merge(
              that.gridCustom.visibleData,
              storeData.visibleData
            );
            gridCustomSave({
              key: zeroCodeId + "_recycleBin",
              title: title,
              config: JSON.stringify({
                fixedData: fixedData,
                resizableData: resizableData,
                sortData: sortData,
                visibleData: visibleData,
              }),
            }).then((result) => {});
            return true;
          },
        },
        pagerConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: columns,
        proxyConfig: {
          seq: true,
          sort: true,
          filter: true,
          props: {
            result: "data",
            total: "count",
          },
          ajax: {
            query: ({ page, sorts, filters }) => {
              if (sorts.length == 0) {
                //再次找默认
                sorts = this.initSorts();
              }
              var gridSort = this.eipGridSort(sorts);
              return new Promise((resolve) => {
                query({
                  zeroCodeId: this.zeroCodeId,
                  current: page.currentPage,
                  size: page.pageSize,
                  status: 9,
                  timeStamp: option.style.cache
                    ? null
                    : this.$utils.timestamp(), //时间戳:可通过设置该值达到不读取缓存数据效果
                  sort: gridSort ? gridSort : "id desc",
                  filters: this.eipTableFilter(filters),
                }).then((result) => {
                  if (result.code == this.eipResultCode.success) {
                    resolve(result.data);
                  } else {
                    this.$message.error(result.msg);
                    resolve({
                      data: [],
                    });
                  }
                });
              });
            },
          },
        },
      };

      that.grid.loading = false;
    },

    /**
     * 转换类型
     * @param row
     * @param column
     */
    convertType(column) {
      var columnFind = this.$utils.find(
        this.columnJson,
        (f) => f.key == column.field
      );
      if (columnFind) {
        return columnFind.type;
      } else {
        switch (column.field) {
          case "CreateTime":
          case "UpdateTime":
            return "systime";
          case "CreateUser":
          case "UpdateUser":
            return "sysuser";
        }
      }
    },

    /**
     * 得到Options
     * @param column
     */
    getOptions(column) {
      return this.$utils.find(this.columnJson, (f) => f.key == column.field);
    },
    /**
     * 初始化列表
     */
    initGrid() {
      let that = this;
      VxeUI.loading.open();
      findById(this.zeroCodeId).then((result) => {
        that.formZeroCodeId = result.data.formZeroCodeId;
        that.publicJson = that.$utils.merge(
          that.$utils.clone(that.eipZeroCodeView, true),
          that.$utils.toStringJSON(result.data.publicJson)
        );
        that.settingJson = JSON.parse(result.data.settingJson);
        that.columnJson = JSON.parse(result.data.columnJson);
        that.title = result.data.name;
        that.initGridOption();
        VxeUI.loading.close();
      });
    },

    /**
     * 初始化列
     */
    async initColumn() {
      let that = this;
      let option = this.publicJson;
      let data = option.field.data;

      let columns = [];

      data.forEach((element) => {
        let columnFind = that.$utils.find(
          that.columnJson,
          (f) => f.key == element.key
        );
        let column = {
          field: element.key,
          title: element.label,
          width: element.width,
          sortable: true,
          slots: {},
          showOverflow: "ellipsis",
          filterRender: {
            name: "MLFilterRender",
          },
          filters: [
            {
              data: {
                type: "input",
                key: null,
                op: "cn",
                write: null,
                options: [],
              },
            },
          ],
        };
        //处理格式化
        if (columnFind) {
          switch (columnFind.type) {
            case that.eipZeroCodeControl.radio:
            case that.eipZeroCodeControl.checkbox:
            case that.eipZeroCodeControl.select:
              let options = [];
              columnFind.options.options.forEach((element) => {
                options.push({
                  value: element.value,
                  label: element.label,
                  checked: false,
                  color: columnFind.options.optionsColor ? element.color : null,
                });
              });
              column.filters = [
                {
                  data: {
                    type: "select",
                    key: null,
                    op: "jcn",
                    write: null,
                    options: options,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.number:
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.switch:
              column.filters = [
                {
                  data: {
                    type: "switch",
                    key: null,
                    op: "cn",
                    write: null,
                    options: [
                      {
                        value: 1,
                        label: "是",
                        checked: false,
                        color: "red",
                      },
                      {
                        value: 0,
                        label: "否",
                        checked: false,
                        color: "#1890ff",
                      },
                    ],
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.rate:
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.slider:
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.uploadFile:
            case that.eipZeroCodeControl.uploadImg:
              break;
            case that.eipZeroCodeControl.editor:
              column.type = "html";
              break;
            case that.eipZeroCodeControl.date:
              column.filters = [
                {
                  data: {
                    type: "datetime",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
          }
          if (columnFind.type != that.eipZeroCodeControl.editor) {
            column.slots.default = "default";
          }
          columns.push(column);
        }

        //判断是否为系统字段
        switch (element.key) {
          case "CreateTime":
          case "UpdateTime":
            column.filters = [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ];
            if (element.key == "UpdateTime") {
              column.title = "删除时间";
            }

            columns.push(column);
            break;
          case "RowId":
            column.filters = [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ];
            columns.push(column);
            break;
          case "CreateUser":
          case "UpdateUser":
            column.filters = [
              {
                data: {
                  type: "user",
                  op: "cn",
                  write: null,
                },
              },
            ];
            if (element.key == "UpdateUser") {
              column.title = "删除人";
            }
            column.slots.default = "default";
            columns.push(column);
            break;
        }
      });

      //获取grid
      var gridCustom = await gridCustomFindByKey(
        this.zeroCodeId + "_recycleBin"
      );
      if (gridCustom.data != null && gridCustom.data.config != null) {
        var config = JSON.parse(gridCustom.data.config);
        if (config.resizableData) {
          var resizableDataKey = that.$utils.keys(config.resizableData);
          resizableDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.width = config.resizableData[key];
            }
          });
          that.gridCustom.resizableData = config.resizableData;
        }
        //固定
        if (config.fixedData) {
          var fixedDataKey = that.$utils.keys(config.fixedData);
          fixedDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.fixed = config.fixedData[key];
            }
          });
          that.gridCustom.fixedData = config.fixedData;
        }
        //隐藏显示
        if (config.visibleData) {
          var visibleDataKey = that.$utils.keys(config.visibleData);
          visibleDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.visible = config.visibleData[key];
            }
          });
          that.gridCustom.visibleData = config.visibleData;
        }
        let cloneColumns = [];
        //顺序
        var sortDataKey = that.$utils.keys(config.sortData);
        if (config.sortData && sortDataKey.length > 0) {
          let sortArray = [];
          sortDataKey.forEach((key) => {
            sortArray.push({
              key: key,
              value: config.sortData[key],
            });
          });
          sortArray = that.$utils.orderBy(sortArray, "value");
          sortArray.forEach((sort) => {
            var columnsFind = that.$utils.find(
              columns,
              (f) => f.field == sort.key
            );
            if (columnsFind) {
              cloneColumns.push(columnsFind);
            }
          });
          columns = cloneColumns;
          that.gridCustom.sortData = config.sortData;
        }
      }

      //是否显示序号
      if (option.style.seq) {
        columns.unshift({
          type: "seq",
          width: 60,
          fixed: "left",
          resizable: false,
          slots: {
            header: "seq",
            default: "seqdefalut",
          },
        });
      }

      if (option.style.select == "checkbox") {
        columns.unshift({
          type: "checkbox",
          width: 50,
          align: "center",
          fixed: "left",
          resizable: false,
          slots: {
            checkbox: "checkbox",
            header: "checkboxHeader",
          },
        });
      }

      return columns;
    },

    /**
     * 得到排序
     */
    initSorts() {
      //默认排序
      let option = this.publicJson;
      var defaultSort = [];
      option.sort.forEach((item) => {
        defaultSort.push({ field: item.key, order: item.sord });
      });
      return defaultSort;
    },

    /**
     * 列表数据
     */
    reloadData() {
      if (this.$refs.recycleBin) this.$refs.recycleBin.commitProxy("query");
    },
    /**
     * 恢复
     */
    delRecovery() {
      let that = this;
      selectTableRow(
        that.$refs.recycleBin,
        function (rows) {
          //提示是否删除
          operationConfirm(
            "确认恢复选中数据",
            function () {
              that.$loading.show({ text: "正在恢复中..." });
              let ids = that.$utils.map(rows, (item) => item.RowId);
              delRecovery({
                zeroCodeId: that.formZeroCodeId,
                id: ids.join(","),
              }).then((result) => {
                that.$loading.hide();
                if (result.code == that.eipResultCode.success) {
                  that.reloadData();
                  that.$emit("ok", result);
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            },
            that
          );
        },
        that,
        false
      );
    },

    /**
     * 列表数据
     */
    reloadData() {
      if (this.$refs.recycleBin) this.$refs.recycleBin.commitProxy("query");
    },

    /**
     * 删除
     */
    delPhysics() {
      let that = this;
      selectTableRow(
        that.$refs.recycleBin,
        function (rows) {
          //提示是否删除
          deleteConfirm(
            that.eipMsg.delete,
            function () {
              that.$loading.show({ text: that.eipMsg.delloading });
              let ids = that.$utils.map(rows, (item) => item.RowId);
              delPhysics({
                zeroCodeId: that.formZeroCodeId,
                id: ids.join(","),
              }).then((result) => {
                that.$loading.hide();
                if (result.code == that.eipResultCode.success) {
                  that.reloadData();
                  that.$emit("ok", result);
                  that.$message.success(result.msg);
                } else {
                  that.$message.error(result.msg);
                }
              });
            },
            that
          );
        },
        that,
        false
      );
    },
    /**
     * 删除所有
     */
    delPhysicsAll() {
      let that = this;
      deleteConfirm(
        that.eipMsg.delete,
        function () {
          that.$loading.show({ text: that.eipMsg.delloading });
          delPhysicsAll({
            id: that.formZeroCodeId,
          }).then((result) => {
            that.$loading.hide();
            if (result.code == that.eipResultCode.success) {
              that.reloadData();
              that.$emit("ok", result);
              that.$message.success(result.msg);
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },
    /**
     *
     * @param param0
     */
    cellStyle({ row }) {
      let that = this;
      let option = this.publicJson;

      var value = row[option.color.field];
      let columnJson = this.$utils.find(
        this.columnJson,
        (f) =>
          f.type == that.eipZeroCodeControl.radio && f.key == option.color.field
      );

      if (columnJson && value && JSON.parse(value).length > 0) {
        var valueJson = JSON.parse(value);
        //是否全部
        if (
          option.color.displayType == "all" ||
          (option.color.display.length > 0 &&
            option.color.display.includes(valueJson[0]))
        ) {
          var find = this.$utils.find(
            columnJson.options.options,
            (f) => f.value == valueJson[0]
          );
          var backgroundColor = this.getLightColor(find.color, 0.8);
          return {
            backgroundColor: [1, 2].includes(option.color.showType)
              ? backgroundColor
              : "",
            showTypeColor: find.color,
            showType: option.color.showType,
          };
        }
      }
    },
  },
};
</script>
